package com.bee.plus.store.service.impl;

import com.bee.plus.dto.ContentReq;
import com.bee.plus.dto.MessageResp;
import com.bee.plus.store.service.StoreChatService;
import com.bee.plus.vo.ChatContentVo;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xupei
 */
@Service("localChatService")
public class LocalStoreChatServiceImpl implements StoreChatService {

    private Logger logger= LoggerFactory.getLogger(LocalStoreChatServiceImpl.class);

    private static final Cache<Long, List<ContentReq>> loadingCache = CacheBuilder.newBuilder().expireAfterAccess(30, TimeUnit.MINUTES).maximumSize(1024).build();



    @Override
    public void storeChatInfo(ContentReq contentReq,Long conversationId) {

        List<ContentReq> list=  getContentHistoryByConversationId(conversationId);
        list.add(contentReq);
        loadingCache.put(conversationId,list);
        logger.info("store {}",conversationId);
    }


    @Override
    public void storeChatInfo(MessageResp messageResp, Long conversationId) {
        ContentReq contentVo=new ContentReq();
        contentVo.setContent(messageResp.getContent());
        contentVo.setRole(messageResp.getRole());
        storeChatInfo(contentVo,conversationId);
    }

    @Override
    public ContentReq getLastChatContentById(Long conversationId) {

        List<ContentReq> list= getContentHistoryByConversationId(conversationId);
        if(list==null||list.size()==0){
            return null;
        }
        return list.get(list.size()-1);
    }

    @Override
    public List<ContentReq> getContentHistoryByConversationId(Long conversationId) {
        List<ContentReq> list=  loadingCache.getIfPresent(conversationId);
        if(list==null){
            list=new ArrayList<>();
        }
        List tempList=new ArrayList();
        for(ContentReq contentReq:list){
            tempList.add(contentReq);
        }
        return tempList;
    }
}
